﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Core.Infrastructure.CommandExtensions
{
    public class CheckBoxUnchecked
    {
        private static readonly DependencyProperty CheckBoxUncheckedProperty = DependencyProperty.RegisterAttached(
            "CheckBoxUnchecked",
            typeof(CheckBoxUncheckedCommandBehavior),
            typeof(CheckBoxUnchecked),
            null);

        private static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
            "Command",
            typeof(ICommand),
            typeof(CheckBoxUnchecked),
            new PropertyMetadata(OnSetCommandCallback));

        public static void SetCommand(CheckBox checkBox, ICommand command)
        {
            checkBox.SetValue(CommandProperty, command);
        }

        public static ICommand GetCommand(CheckBox checkBox)
        {
            return checkBox.GetValue(CommandProperty) as ICommand;
        }

        private static void OnSetCommandCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            var checkBox = dependencyObject as CheckBox;
            if (checkBox != null)
                GetOrCreateBehavior(checkBox).Command = e.NewValue as ICommand;
        }

        private static CheckBoxUncheckedCommandBehavior GetOrCreateBehavior(CheckBox checkBox)
        {
            var behavior = checkBox.GetValue(CheckBoxUncheckedProperty) as CheckBoxUncheckedCommandBehavior;
            if (behavior == null)
            {
                behavior = new CheckBoxUncheckedCommandBehavior(checkBox);
                checkBox.SetValue(CheckBoxUncheckedProperty, behavior);
            }

            return behavior;
        }

    }
}
